<script>
	import {
		HTTP_REQUEST_URL
	} from './config/app';
	import Auth from './libs/wechat.js';
	import Routine from './libs/routine.js';
	import {
		getTheme
	} from './api/api.js';
	import {
		mapActions
	} from 'vuex'
	import {
		spread
	} from "@/api/user";
	import Cache from './utils/cache.js';
	import store from './store'
	var statusBarHeight = uni.getSystemInfoSync().statusBarHeight; //手机端头部手机时间位置高度
	
	// #ifdef APP-PLUS
		var jpushModule = uni.requireNativePlugin("JG-JPush");
		var audioObj = uni.getBackgroundAudioManager();
	// #endif
	
	export default {
		globalData: {
			spread: 0,
			isLogin: false,
			windowHeight: 0,
			navHeight: 0, //导航高度
			navH: 0,
			id: 0, // 小程序扫码进入商品id，首页id
			isIframe: false,
			theme: Cache.get('theme') ? Cache.get('theme') : 'theme1',
			statusBarHeight: statusBarHeight, //手机端头部手机时间位置高度
			mainWidth: 0 ,//获取设备宽度
			type: '' //商品类型，normal普通商品
		},
		onLaunch: function(option) {
			let that = this;
			console.log(option.query);
			// 主题变色
			getTheme().then(resP => {
				Cache.set('theme', `theme${Number(resP.data.value)}`);
				that.globalData.theme = `theme${Number(resP.data.value)}`;
				// #ifdef H5
				window.document.documentElement.setAttribute('data-theme', that.globalData.theme);
				// #endif
				store.commit('GLOBAL_DATA', that.globalData);
				
			})	
			
			if (option.query.spread) {
				that.globalData.spread = option.query.spread;
				store.commit('GLOBAL_DATA', JSON.parse(JSON.stringify(that.globalData)));
			}
			if (option.spread) {
				that.globalData.spread = option.spread;
				store.commit('GLOBAL_DATA', JSON.parse(JSON.stringify(that.globalData)));
			}
			uni.getSystemInfo({
				success: function(res) {
					// 首页没有title获取的整个页面的高度，里面的页面有原生标题要减掉就是视口的高度  
					// 状态栏是动态的可以拿到 标题栏是固定写死的是44px
					let height = res.windowHeight - res.statusBarHeight - 44;
					// #ifdef H5 || APP-PLUS
					that.globalData.windowHeight = res.windowHeight + 'px';
					// #endif
					// 获取导航高度；
					that.globalData.navHeight = res.statusBarHeight * (750 / res.windowWidth) + 91;
					// 获取设备宽度；
					that.globalData.mainWidth = res.windowWidth
					store.commit('SYSTEM_PLATFORM', res.platform.toLowerCase());
				}
			});

			
			// #ifdef APP-PLUS
			//that.moveToBack();
			// #endif
			// #ifdef MP
			if (option.query.hasOwnProperty('scene')) {
				switch (option.scene) {
					case 1001: //直接进入小程序
					case 1047: //扫描小程序码
					case 1048: //长按图片识别小程序码
					case 1049: //手机相册选取小程序码
					case 1001: //直接进入小程序
						let value = this.$util.getUrlParams(decodeURIComponent(option.query.scene));
						that.globalData.spread = value.spread?value.spread:'';
						that.globalData.id = value.id?value.id:'';
						that.globalData.type = value.type?value.type:'normal';
						break;
				}
			}
			if (option.spread) that.globalData.spread = option.spread;
			let menuButtonInfo = uni.getMenuButtonBoundingClientRect();
			that.globalData.navH = menuButtonInfo.top * 2 + menuButtonInfo.height / 2;
			const updateManager = uni.getUpdateManager();
			updateManager.onCheckForUpdate(function(res) {
				// 请求完新版本信息的回调
				if (res.hasUpdate) {
					updateManager.onUpdateReady(function(res2) {
						uni.showModal({
							title: '更新提示',
							content: '发现新版本，是否重启应用?',
							cancelColor: '#eeeeee',
							confirmColor: '#FF0000',
							success(res2) {
								if (res2.confirm) {
									// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
									updateManager.applyUpdate();
								}
							}
						});
					});
				}
			});

			updateManager.onUpdateFailed(function(res) {
				// 新的版本下载失败
				uni.showModal({
					title: '提示',
					content: '检查到有新版本，但下载失败，请检查网络设置',
					success(res) {
						if (res.confirm) {
							// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
							updateManager.applyUpdate();
						}
					}
				});
			});

			if (HTTP_REQUEST_URL == '') {
				console.error(
					"请配置根目录下的config.js文件中的 'HTTP_REQUEST_URL'\n\n请修改开发者工具中【详情】->【AppID】改为自己的Appid\n\n请前往后台【小程序】->【小程序配置】填写自己的 appId and AppSecret"
				);
				return false;
			}
			// #endif
			// #ifdef H5	
			if (option.query.hasOwnProperty('type') && option.query.type == "iframeVisualizing") {
				this.globalData.isIframe = true;
			} else {
				this.globalData.isIframe = false;
			}

			let snsapiBase = 'snsapi_base';
			let urlData = location.pathname + location.search;
			console.log(urlData);
			if (!store.getters.isLogin && Auth.isWeixin()) {
				const {
					code,
					state,
					scope
				} = option.query;
				if (code && code != uni.getStorageSync('snsapiCode') && location.pathname.indexOf(
						'/pages/users/wechat_login/index') === -1) {
					// 存储静默授权code
					uni.setStorageSync('snsapiCode', code);
					let spread = that.globalData.spread ? that.globalData.spread : 0;
					Auth.auth(code, Cache.get('spread'))
						.then(res => {
							uni.setStorageSync('snRouter', decodeURIComponent(decodeURIComponent(option.query
								.back_url)));
							if (res.type === 'register') {
								Cache.set('snsapiKey', res.key);
							}
							if (res.type === 'login') {
								store.commit('LOGIN', {
									token: res.token
								});
								store.commit("SETUID", res.id);
								location.replace(decodeURIComponent(decodeURIComponent(option.query.back_url)));
							}
						})
						.catch(error => {
							if (!Cache.has('snsapiKey')) {
								if (location.pathname.indexOf('/pages/users/wechat_login/index') === -1) {
									Auth.oAuth(snsapiBase, '/pay/rygmall/'+option.query.back_url);
								}
							}
						});
				} else {
					if (!Cache.has('snsapiKey')) {
						if (location.pathname.indexOf('/pages/users/wechat_login/index') === -1) {
							Auth.oAuth(snsapiBase, '/pay/rygmall/'+urlData);
						}
					}
				}
			} else {
				if (option.query.back_url) {
					location.replace(uni.getStorageSync('snRouter'));
				}
			}
			// #endif

			// #ifdef MP
			// 小程序静默授权
			if (!store.getters.isLogin) {
				Routine.getCode().then(code => {
						let userInfo = {
							code: code,
							spreadPid: this.globalData.spread, //获取推广人ID
							type: 'routine'
						};
						Routine.authUserInfo(userInfo)
					})
					.catch(res => {
						uni.hideLoading();
					});
			}
			// #endif
			if (store.getters.isLogin && this.globalData.spread) {
				spread(this.globalData.spread).then(res => {}).catch(res => {})
			}

			// uni.getSystemInfo({
			// 	success: function(res) {
			// 		// 获取导航高度；
			// 		that.globalData.navHeight = res.statusBarHeight * (750 / res.windowWidth) + 91;
			// 		// 获取设备宽度；
			// 		that.globalData.mainWidth = res.windowWidth
			// 	}
			// });
			// #ifdef APP-PLUS
			jpushModule.initJPushService();
			jpushModule.setLoggerEnable(true);
			plus.screen.lockOrientation("portrait-primary");
			// 设置别名
			// jpushModule.setAlias({
			// 		// 'alias': 'riyegou' + this.globalData.userInfo.userId,
			// 		'alias': 'RYG202406121618',
			// 		'sequence': 1
			// });
			//监听 极光推送连接状态
			this.getNotificationEnabled();
			jpushModule.addConnectEventListener(result => {
				let connectEnable = result.connectEnable
				uni.$emit('connectStatusChange', connectEnable)
			});
			jpushModule.addNotificationListener(result => { //极光推送的消息通知回调
				jpushModule.setBadge(0);
				plus.runtime.setBadgeNumber(0);
				let notificationEventType = result.notificationEventType
				let woopId = result.extras && result.extras.dataType === 'woop' && result.extras.value;
				console.log("通知", result, notificationEventType)
				// 点击事件
				if (notificationEventType == 'notificationOpened') {
					uni.navigateTo({
						url: '/pages/taskDetail/taskDetail?' + 'woopId=' + woopId
					});
				}
			});
			uni.$on('connectStatusChange', (connectStatus) => {
				var connectStr = ''
				if (connectStatus == true) {
					connectStr = '已连接'
					// this.getRegistrationID()
				} else {
					connectStr = '未连接'
				}
				console.log('监听到了连接状态变化 --- ', connectStr)
				this.connectStatus = connectStr
			})
			jpushModule.isPushStopped(res => {
				// code   0已停止推送  1未停止推送
				const { code } = res
				console.log(res, '安卓连接状态');
			})
			//#endif

			store.commit('GLOBAL_DATA', JSON.parse(JSON.stringify(that.globalData)));
		},
		async mounted() {
			//if (this.$store.getters.isLogin && !this.$Cache.get('USER_INFO')) await this.$store.dispatch('USERINFO');
		},
		methods: {
			moveToBack() {
				// 隐藏“再按一次退出应用”的提示，将应用隐藏至后台
				// let main = plus.android.runtimeMainActivity();
				// if (store.getters.systemPlatform) {
				// 	plus.runtime.quit = function() {
				// 		main.moveTaskToBack(false);
				// 	};
				// }

				//重写toast方法如果内容为 ‘再按一次退出应用’ 就隐藏应用，其他正常toast
				// plus.nativeUI.toast = (function(str){
				// 	if(str == '再按一次退出應用'){
				// 		main.moveTaskToBack(false);
				// 		return false;
				// 	}else{
				// 		uni.showToast({
				// 			title:str,
				// 			icon:'none',
				// 		})
				// 	}
				// });
			},
			getRegistrationID() { //获取registerID
				jpushModule.getRegistrationID(result => {
					let registerID = result.registerID
					console.log(registerID)
					this.registrationID = registerID
					uni.setStorageSync("registerID", registerID)
				})
			},
			getNotificationEnabled() {
				if (uni.getSystemInfoSync().platform == "ios") {
					jpushModule.requestNotificationAuthorization((result) => {
						let status = result.status
						if (status < 2) {
							this.noticMsgTool()
						}
					})
				} else {
					jpushModule.isNotificationEnabled((result) => { //判断android是否打开权限
						if (result.code == 0) { //如果为0则表示 未打开通知权限 
							this.noticMsgTool()
						}
					})
				}
			},
			noticMsgTool() {
				if (uni.getSystemInfoSync().platform == "ios") {
					//苹果打开对应的通知栏
					uni.showModal({
						title: '通知权限开启提醒',
						content: '您还没有开启通知权限，无法接受到消息通知，请前往设置！',
						showCancel: false,
						confirmText: '去设置',
						success: function(res) {
							if (res.confirm) {
								var app = plus.ios.invoke('UIApplication', 'sharedApplication');
								var setting = plus.ios.invoke('NSURL', 'URLWithString:', 'app-settings:');
								plus.ios.invoke(app, 'openURL:', setting);
								plus.ios.deleteObject(setting);
								plus.ios.deleteObject(app);
							}
						}
					});
				} else {
					//android打开对应的通知栏
					var main = plus.android.runtimeMainActivity();
					var pkName = main.getPackageName();
					var uid = main.getApplicationInfo().plusGetAttribute("uid");
					uni.showModal({
						title: '通知权限开启提醒',
						content: '您还没有开启通知权限，无法接受到消息通知，请前往设置！',
						showCancel: false,
						confirmText: '去设置',
						success: function(res) {
							if (res.confirm) {
								var Intent = plus.android.importClass('android.content.Intent');
								var Build = plus.android.importClass("android.os.Build");
								//android 8.0引导  
								if (Build.VERSION.SDK_INT >= 26) {
									var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
									intent.putExtra('android.provider.extra.APP_PACKAGE', pkName);
								} else if (Build.VERSION.SDK_INT >= 21) { //android 5.0-7.0  
									var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
									intent.putExtra("app_package", pkName);
									intent.putExtra("app_uid", uid);
								} else { //(<21)其他--跳转到该应用管理的详情页  
									intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
									var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
									intent.setData(uri);
								}
								// 跳转到该应用的系统通知设置页  
								main.startActivity(intent);
							}
						}
					});
				}
			},

		},
		onShow: function() {
			// #ifdef H5
			uni.getSystemInfo({
				success(e) {
					/* 窗口宽度大于420px且不在PC页面且不在移动设备时跳转至 PC.html 页面 */
					if (e.windowWidth > 420 && !window.top.isPC && !/iOS|Android/i.test(e.system)) {
						// window.location.pathname = 'https://java.crmeb.net/';
						/* 若你的项目未设置根目录（默认为 / 时），则使用下方代码 */
						// window.location.pathname = '/pay/rygmall/static/html/pc.html';
						window.location.pathname = '/pay/rygmall/static/html/pc.html';
					}
				}
			})
			// #endif
		},
		onHide: function() {}
	}
</script>
<style lang="scss">
	/* #ifndef APP-PLUS-NVUE || APP-NVUE */
	@import "@/plugin/animate/animate.min.css";
	@import 'static/css/base.css';
	@import 'static/iconfont/iconfont.css';
	@import 'static/iconfont/iconfont-weapp-icon.css';
	@import 'static/css/guildford.css';
	@import 'static/css/style.scss';


	view {
		box-sizing: border-box;
	}

	body::-webkit-scrollbar,
	html::-webkit-scrollbar {
		display: none;
	}

	.bg-color-red {
		background-color: #E93323;
	}

	.syspadding {
		padding-top: var(--status-bar-height);
	}

	.flex {
		display: flex;
	}

	/deep/.uni-scroll-view::-webkit-scrollbar {
		/* 隐藏滚动条，但依旧具备可以滚动的功能 */
		display: none
	}

	::-moz-scrollbar {
		width: 0;
		height: 0;
		color: transparent;
	}

	::-webkit-scrollbar {
		display: none;
		width: 0 !important;
		height: 0 !important;
		-webkit-appearance: none;
		background: transparent;
	}
	/*#endif*/
</style>